package com.hup.sokoban.service.mapDesigner;

import com.hup.sokoban.constant.MapConstant.ElementType;
import com.hup.sokoban.view.customView.MapLabel;
import lombok.extern.log4j.Log4j2;

import javax.swing.SwingUtilities;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

/**
 * 鼠标绘图功能类
 *
 * @author hugan
 * @date 2020/5/2
 */
@Log4j2
public class MapLabelDrawingGesture extends MouseAdapter {

    public static void bind(MapLabel mapLabel, Handler handler) {
        MapLabelDrawingGesture gesture = new MapLabelDrawingGesture(mapLabel, handler);
        mapLabel.addMouseListener(gesture);
        mapLabel.addMouseMotionListener(gesture);
    }

    private final MapLabel mapLabel;
    private final Handler handler;
    //按下时更新
    /**
     * 当前的元素
     */
    private ElementType elementType;
    private int lastIndex = -1;

    private MapLabelDrawingGesture(MapLabel mapLabel, Handler handler) {
        this.mapLabel = mapLabel;
        this.handler = handler;
    }

    @Override
    public void mousePressed(MouseEvent e) {
        if (SwingUtilities.isLeftMouseButton(e)) {
            elementType = handler.getDrawingElementType();
        } else if (SwingUtilities.isRightMouseButton(e)) {
            //右键擦除
            elementType = ElementType.EMPTY;
        } else {
            return;
        }
        lastIndex = -1;//每次按下时,要重置
        mouseDragged(e);
    }

    @Override
    public void mouseDragged(MouseEvent e) {
        if (!SwingUtilities.isLeftMouseButton(e) && !SwingUtilities.isRightMouseButton(e)) return;

        int cellIndex = mapLabel.getCellIndex(e);
        if (cellIndex == -1) return;
        if (lastIndex == cellIndex) return;
        lastIndex = cellIndex;
        log.debug("lastIndex={}", lastIndex);

        int[] map = mapLabel.getMapItem().getMap();
        map[lastIndex] = elementType.intValue;
        mapLabel.getMapItem().resetDesigningFields();
        mapLabel.notifyDataUpdated();
    }

    public interface Handler {

        /**
         * @return 绘制面板当前的元素
         */
        ElementType getDrawingElementType();

    }

}
